<template>
  <div class="order-list-container">
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <el-button type="primary" @click="$router.push('/order/add')">新增订单</el-button>
    </div>

    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input v-model="searchForm.orderNo" placeholder="订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.username" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="订单状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="orderNo" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="items" label="商品数量" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.items.length }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalPoints" label="积分" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.totalPoints }} 分</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template slot-scope="scope">{{ scope.row.createdAt || '-' }}</template>
        </el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">查看</el-button>
            <el-button
              v-if="scope.row.status === '待发货'"
              type="text"
              size="small"
              @click="handleShip(scope.row)"
            >发货</el-button>
            <el-button
              v-if="scope.row.status === '待付款'"
              type="text"
              size="small"
              class="delete-btn"
              @click="handleCancel(scope.row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getOrderList, cancelOrder, shipOrder, deleteOrder } from '@/api/order'

export default {
  name: 'OrderList',
  data() {
    return {
      searchForm: {
        orderNo: '',
        username: '',
        status: '',
        dateRange: [],
      },
      statusOptions: [
        { value: '待付款', label: '待付款' },
        { value: '待发货', label: '待发货' },
        { value: '已发货', label: '已发货' },
        { value: '已完成', label: '已完成' },
        { value: '已取消', label: '已取消' },
      ],
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.loading = true

      // 构建查询参数
      const params = {
        page: this.currentPage,
        limit: this.pageSize,
      }

      // 添加筛选条件
      if (this.searchForm.orderNo) {
        params.orderNo = this.searchForm.orderNo
      }
      if (this.searchForm.username) {
        params.username = this.searchForm.username
      }
      if (this.searchForm.status) {
        params.status = this.searchForm.status
      }
      if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
        params.startDate = this.searchForm.dateRange[0]
        params.endDate = this.searchForm.dateRange[1]
      }

      // 调用API获取订单列表
      getOrderList(params)
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.list || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.message || '获取订单列表失败')
          }
        })
        .catch(error => {
          console.error('获取订单列表出错', error)
          this.$message.error('获取订单列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    getStatusType(status) {
      switch (status) {
        case '待付款':
          return 'warning'
        case '待发货':
          return 'primary'
        case '已发货':
          return 'success'
        case '已完成':
          return 'success'
        case '已取消':
          return 'info'
        default:
          return ''
      }
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        orderNo: '',
        username: '',
        status: '',
        dateRange: [],
      }
      this.handleSearch()
    },
    handleEdit(row) {
      this.$router.push(`/order/add?id=${row.id}`)
    },
    handleShip(row) {
      this.$confirm('确认发货该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true
          shipOrder(row.id)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('发货成功')
                this.fetchData() // 重新加载列表
              } else {
                this.$message.error(res.message || '发货失败')
              }
            })
            .catch(error => {
              console.error('发货失败', error)
              this.$message.error('发货失败')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },
    handleCancel(row) {
      this.$confirm('确认取消该订单吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true
          cancelOrder(row.id)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('订单已取消')
                this.fetchData() // 重新加载列表
              } else {
                this.$message.error(res.message || '取消订单失败')
              }
            })
            .catch(error => {
              console.error('取消订单失败', error)
              this.$message.error('取消订单失败')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
  },
}
</script>

<style scoped>
.order-list-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.search-container {
  background: #ffffff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
  flex: 0 0 240px;
}

.table-container {
  background: #ffffff;
  padding: 24px;
  border-radius: 8px;
}

.el-table {
  margin-top: 16px;
}

.el-table th {
  background-color: #f7f7f7;
  color: #4d4d4d;
  font-weight: 600;
  height: 48px;
}

.el-table td {
  color: #666666;
  height: 56px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #f53f3f;
}

.delete-btn:hover {
  color: #f78989;
}
</style> 